/**
 * File    : ChoosePersona.java
 * Created : 2008-10-19
 * By      : LuHuiguo
 */
package com.luhuiguo.sso.web.pages.secure.persona;

import java.security.Principal;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.services.PropertyAccess;
import org.apache.tapestry5.services.RequestGlobals;

import com.luhuiguo.sso.entity.Persona;
import com.luhuiguo.sso.entity.User;
import com.luhuiguo.sso.service.UserManager;
import com.luhuiguo.tapestry.model.GenericSelectModel;

/**
 * @author LuHuiguo
 * @version $Id: ChoosePersona.java 20 2008-10-19 15:43:48Z LuHuiguo $
 * 
 */
public class ChoosePersona {

	@Inject
	private Messages messages;

	@Inject
	private RequestGlobals requestGlobals;

	@Inject
	private PropertyAccess propertyAccess;

	@Inject
	private UserManager userManager;


	@Persist("flash")
	private GenericSelectModel<Persona> personaModel;

	@Persist
	private User user;



	Object initialize(User user) {
		this.user = user;
		return this;
	}	

	public String getUsername() {
		Principal principal = requestGlobals.getHTTPServletRequest()
				.getUserPrincipal();
		return principal == null ? "" : principal.getName();
	}
	
	@OnEvent(EventConstants.ACTIVATE)
	void onActivate() {
		if (user == null) {
			user = userManager.getUser(getUsername());
		}
	}

	@SetupRender
	void setupRender() throws Exception {
		personaModel = new GenericSelectModel<Persona>(user.getPersonas(),
				Persona.class, "name", "name", propertyAccess);
	}

	public GenericSelectModel<Persona> getPersonaModel() {
		return personaModel;
	}

	public void setPersonaModel(GenericSelectModel<Persona> personaModel) {
		this.personaModel = personaModel;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	

}
